/**
* All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
*
* PmTaskLogService
* 任务工作日志
*
* 修改纪录
* 2020-05-15 版本：1.0 wushenghong 创建。
* @version 版本：1.0
* @author 作者：wushenghong
* 创建日期：2020-05-15
*/
package com.topscomm.pm.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.BusinessException;
import com.topscomm.basic.exception.MessageException;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboApprovalNodeEntity;
import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.cbo.pojo.CboDeptEntity;
import com.topscomm.cbo.pojo.CboOrgEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.impl.CboDeptService;
import com.topscomm.cbo.service.impl.CboOrgService;
import com.topscomm.pm.pojo.PmCalendarEntity;
import com.topscomm.pm.pojo.PmTaskLogEntity;
import com.topscomm.pm.service.IPmTaskLogService;
import com.topscomm.pm.service.impl.auto.PmTaskLogServiceAuto;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.common.ParameterCache;
import com.topscomm.tap.common.SessionUserBean;
import java.math.BigDecimal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(value = "pmTaskLogService")
@Scope(value = "singleton")
public class PmTaskLogService extends PmTaskLogServiceAuto implements IPmTaskLogService {
	private final Logger logger = LoggerFactory.getLogger(PmTaskLogService.class);
	/**
	 * @author: wushenghong
	 * @date: 2020-05-15
	 * @param entity
	 * @throws ServiceException
	 * @description:单号生成
	 * @modify:
	 */
	@Override
	protected void beforeInsert(BasicEntity entity){
		super.beforeInsert(entity);
		if (entity.getId() <= 0) {// 赋值Id和单号
			long[] arrayId = PrimaryKeyUtil.GeneIDs(entity.getTableName(), 1);
			entity.setId(arrayId[0]);
			String docNo = String.valueOf(arrayId[0]);
			docNo = docNo.substring(0, 6) + docNo.substring(9);
			entity.setValue(PmTaskLogEntity.FieldDocno, docNo);
		}
	}


	/**
	 * @author: wushenghong
	 * @date: 2020/6/6
	 * @description: 根据工号查询部门组织信息
	 */
	public Map<String, Object> queryOrgAndDeptByCode(String code) {
		Map<String, Object> orgAndDeptMap = new HashMap<>();
		CboOrgService cboOrgService = (CboOrgService) SpringUtil.getBean("cboOrgService");
		CboDeptService cboDeptService = (CboDeptService) SpringUtil.getBean("cboDeptService");
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("id in (select orgid from cbouser where code = '{0}')", code);
		List<CboOrgEntity> cboOrgEntityList = cboOrgService.queryByWhere(sql.toString());
		sql.clear();
		sql.appendSingle("id in (select deptid from cbouser where code = '{0}')", code);
		List<CboDeptEntity> cboDeptEntityList = cboDeptService.queryByWhere(sql.toString());
		sql.clear();
		orgAndDeptMap.put("orgcode", cboOrgEntityList.size() > 0 ? cboOrgEntityList.get(0).getCode() : "");
		orgAndDeptMap.put("orgname", cboOrgEntityList.size() > 0 ? cboOrgEntityList.get(0).getName() : "");
		orgAndDeptMap.put("deptcode", cboDeptEntityList.size() > 0 ? cboDeptEntityList.get(0).getCode() : "");
		orgAndDeptMap.put("deptname", cboDeptEntityList.size() > 0 ? cboDeptEntityList.get(0).getFullname() : "");
		return orgAndDeptMap;
	}

	/**
	 * @author: wushenghong
	 * @date: 2020/6/6
	 * @description: 根据项目id、当前日期判断是否是工作日
	 */
	public boolean isWorkDate(Long projectId, Date date) {
		StringBufferProxy sql = new StringBufferProxy();
		String datePure = cn.hutool.core.date.DateUtil.formatDate(date);//过滤日期格式
		sql.appendSingle(" enabled=1 ");
		sql.appendSingle("and projectid = {0} and calendardate = {1}", projectId, SQLAdapter.toDateLong(datePure + " 00:00:00"));
		PmCalendarService pmCalendarService = (PmCalendarService) SpringUtil.getBean("pmCalendarService");
		List<PmCalendarEntity> pmCalendarEntityList = pmCalendarService.queryByWhere(sql.toString());
		if (pmCalendarEntityList.size() > 0) {
			PmCalendarEntity pmCalendarEntity = pmCalendarEntityList.get(0);
			String calenderType = pmCalendarEntity.getCalendartype();
			//工作日或者加班日
			return "01".equals(calenderType) || "04".equals(calenderType);
		}
		return false;
	}

	/**
	* @author: sunxl
	* @date: 2020-05-28
	* @params: whereSql 查询条件
	* @params: selectname sql语句的id
	* @return: 查询结果
	* @description:根据whereSql查询
	* @modify:
	*/
	@Override
	public List<Map<String, Object>> queryMapByWhereStatistics(String whereSql, String selectname) {
	    //this.getDao().
	    try {
    		Map<String, Object> map = new HashMap<String, Object>();
    		map.put("whereSql", whereSql);
    		List<Map<String, Object>> listResultMap = this.dao.queryMap(map, selectname);
    		setDispFields(listResultMap);
    		return listResultMap;
	    } catch (Exception e) {
        	throw new ServiceException(e.getMessage());
	    }
	}

	/**
	* @author: sunxl
	* @date: 2020-05-28
	* @params: whereSql 查询条件
	* @params:curPageIndex
        * @params:pageSize
        * @params:sidx
        * @params:sord
	* @params: selectname sql语句的id
	* @return: 查询结果
	* @description:根据whereSql查询
	* @modify:
	*/
	@Override
	public List<Map<String, Object>> queryMapForPageStatistics(String whereSql, int curPageIndex, int pageSize, String sidx, String sord, String selectname) {
	    //this.getDao().
	    try {
    		int beginCount = curPageIndex * pageSize - pageSize;
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("begincount", beginCount);
		paraMap.put("pagesize", pageSize);
		paraMap.put("whereSql", whereSql);
		paraMap.put("sidx", sidx);
		paraMap.put("sord", sord);
    		List<Map<String, Object>> listResultMap = this.dao.queryMap(paraMap,selectname);
    		setDispFields(listResultMap);
    		return listResultMap;
	    } catch (Exception e) {
        	throw new ServiceException(e.getMessage());
	    }
	}

	/**
	* @author: sunxl
	* @date: 2020-05-28
	* @params: whereSql 查询条件
	* @params: selectname sql语句的id
	* @return: 查询结果
	* @description:根据whereSql查询
	* @modify:
	*/
	@Override
	public int getCountStatistics(String whereSql, String selectname) {
	    //this.getDao().
	    try {
    		Map<String, Object> map = new HashMap<String, Object>();
    		map.put("whereSql", whereSql);
    		int num = this.dao.getCount(map, selectname);
    		return num;
	    } catch (Exception e) {
        	throw new ServiceException(e.getMessage());
	    }
	}

	@Override
	public List<Map<String, Object>> getNotFiledJobLogList(Map<String,Object> whereMap) {
		List<Map<String, Object>> list = this.dao.queryMap(whereMap, "getNotFiledJobLogList");
		return list;
	}

	@Override
	public Map<String, Object> getFilledAndCreatAndApprovedCount(CboUserEntity userEntity) {

		String taskLogStatisticsDate = "";
		try {
			taskLogStatisticsDate = ParameterCache.getValue("taskLogStatisticsDate");
		} catch (Exception e) {
			logger.error("获取“作日志时间占比统计上月日期”系统参数失败。");
			throw new ServiceException("获取“作日志时间占比统计上月日期”系统参数失败。");
		}
		String beginDate = DateUtil.format(DateUtil.offsetMonth(new Date(), -1),"yyyy-MM")+"-"+taskLogStatisticsDate;
		Map<String,Object> paramMap = new HashMap<>();
		paramMap.put("beginDate",beginDate);
		paramMap.put("userCode",userEntity.getCode());
		// 获取已提交的日志时间占比之和
		List<Map<String, Object>> list1 = this.dao.queryMap(paramMap, "getFilledTaskLogCount");
		// 已审批的时间日志时间占比之和
		List<Map<String, Object>> list2 = this.dao.queryMap(paramMap, "getApprovaledTaskLogCount");
//		List<Map<String, Object>> list3 = this.dao.queryMap(paramMap, "getCreatedTaskLogCount");
		Map<String,Object> res = new HashMap<>();
		res.put("filledTaskLogCount",list1.get(0));
		res.put("approvaledTaskLogCount",list2.get(0));
//		res.put("createdTaskLogCount",list3.get(0));
		return res;
	}

//	@Override
//	protected void beforeApprove(TapEntity billEntity, CboApprovalNodeInsEntity nodeIns, CboApprovalNodeEntity node, SessionUserBean sessionUserBean) {
//		BigDecimal time = (BigDecimal) billEntity.getValue("timetroportion");
//		StringBufferProxy sql = new StringBufferProxy();
//		if("日志填写".equals(billEntity.getValue("latestphase"))){
//			sql.appendSingle("select  sum(NVL(TIMETROPORTION,0)) as TIMETROPORTIONNUM from PMTASKLOG where USERCODE='{0}' and DOCDATE ={1} and id<>'{2}'",sessionUserBean.getUser().getCode(),SQLAdapter.toDateLong(billEntity.getValue("docdate").toString()),billEntity.getId());
//			List<Map<String, Object>> maps = this.selectExecute(sql.toString());
//			BigDecimal timetroportionnum = ConvertUtil.convertToBigDecimal(maps.get(0).get("timetroportionnum"));
//			BigDecimal addnum = timetroportionnum.add(time);
//			BigDecimal i = addnum.subtract(new BigDecimal("1.0"));
//			if(i.compareTo(BigDecimal.ZERO)>0){
//				throw new MessageException("该日期总的时间占比之和超过1，请重新填写！");
//			}
//		}
//	}
}
